<script setup lang="ts">

import {onMounted, ref} from "vue";
import {Close, Plus} from "@element-plus/icons-vue";
import {ElMessage, ElNotification, UploadProps, UploadRawFile} from "element-plus";
import {VueDraggable} from "vue-draggable-plus";
import {v4 as uuidv4} from "uuid";
import axios from "axios";
import {ServerHost} from "@/main.js";
import PolicyDataAnalysis from "@/components/policyManage/PolicyDataAnalysis.vue";
import ManagePostedPolicy from "@/components/policyManage/ManagePostedPolicy.vue";
import PostOrEditPolicy from "@/components/policyManage/PostOrEditPolicy.vue";


const imgStatus = {
  onLocal: 0, //图片尚未上传
  onUpdated: 1, //原先的图片已经上传了，但现在有所修改
  onCloud: 2, //图片已经上传
}

const carouseList = ref([
  // {id: uuidv4(), status: imgStatus.onLocal, rawFile: UploadRawFile, url: ""},
  // {id: uuidv4(), status: imgStatus.onLocal, rawFile: UploadRawFile, url: ""},
  // {id: uuidv4(), status: imgStatus.onLocal, rawFile: UploadRawFile, url: ""},
  // {id: uuidv4(), status: imgStatus.onLocal, rawFile: UploadRawFile, url: ""},
  // {id: uuidv4(), status: imgStatus.onLocal, rawFile: UploadRawFile, url: ""},
])

const isCarouselImgListLoading = ref(true)
const isCarouselImgListSubmitting = ref(false)

const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          console.log("【首页轮播图管理】正在加载")
          axios.get(`${ServerHost}/getIndexCarouselList`)
              .then(res => {
                carouseList.value = res.data
                isCarouselImgListLoading.value = false
                if (res.status === 200) {
                  hasLoad.value = true
                  console.log("【首页轮播图管理】加载成功")
                  carouseList.value.forEach(item => {
                    item.status = imgStatus.onCloud
                    item.rawFile = base64ToFile(item.imgData, item.id)
                    item.imgUrl = URL.createObjectURL(item.rawFile)
                    // carouseList.value.push(item)
                  })
                } else {
                  ElNotification({
                    title: '轮播图获取失败',
                    type: 'error',
                    position: 'bottom-right',
                  })
                }
              })
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})

const selectedImgId = ref("")

const onAddImg: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {

  if (!verifyImg(rawFile)) {
    return
  }

  const newImg = {id: uuidv4(), status: imgStatus.onLocal, rawFile: rawFile, url: URL.createObjectURL(rawFile)}
  carouseList.value.push(newImg)
}

const onUpdateImg: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {


  if (!verifyImg(rawFile)) {
    return
  }
  const
      selectedImgIndex = getImgIndex(selectedImgId.value)

  carouseList.value[selectedImgIndex].rawFile = rawFile
  carouseList.value[selectedImgIndex].imgUrl = URL.createObjectURL(rawFile)

  switch (carouseList.value[selectedImgIndex].status) {
    case imgStatus.onCloud:
      carouseList.value[selectedImgIndex].status = imgStatus.onUpdated
      break
    case imgStatus.onLocal:
      carouseList.value[selectedImgIndex].status = imgStatus.onLocal
      break
  }
}

const onRemoveImg = (id: string) => {
  console.log('onRemoveImg', id)
  carouseList.value = carouseList.value.filter(img => img.id !== id)

}

const onClickCarouselImgUpload = (id: string) => {
  selectedImgId.value = id;
}

// 通过图片id寻找图片在carouselImgList中的下标
const getImgIndex = (id: string): number => {
  let indexRes = -1
  carouseList.value.forEach((img, index: number) => {
    if (img.id === id) {
      indexRes = index
    }
  })
  return indexRes
}

// 覆盖自带的上传行为
const onImgUpload = () => {
  console.log('onImgUpload')
}

// const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
//   if (rawFile.type !== 'image/jpeg') {
//     ElMessage.error('Avatar picture must be JPG format!')
//     return false
//   } else if (rawFile.size / 1024 / 1024 > 2) {
//     ElMessage.error('Avatar picture size can not exceed 2MB!')
//     return false
//   }
//   return true
// }

// 上传到服务器
const submitCarouselImg = () => {

  isCarouselImgListSubmitting.value = true
  const indexCarouselList = []

  if (carouseList.value.length === 0) {
    postCarouselImg(indexCarouselList)
  } else {
    carouseList.value.forEach((img, index: number) => {
      const reader = new FileReader()

      reader.readAsDataURL(img.rawFile); // 读取文件内容并转换为 Base64 编码字符串
      reader.onload = () => {
        if (typeof reader.result === "string") {
          const indexCarousel = {
            id: "",
            imgData: "",
            url: "",
            priority: 0,
          }
          indexCarousel.id = img.id
          indexCarousel.imgData = reader.result
          indexCarousel.url = img.url
          indexCarousel.priority = index
          indexCarouselList.push(indexCarousel)
        }
        //  已读取最后一个
        if (index === carouseList.value.length - 1) {
          postCarouselImg(indexCarouselList)
        }
      }
    })
  }
}

function base64ToFile(base64: string, fileName: string) {
  let arr = base64.split(",");
  // let mime = arr[0].match(/:(.\*?);/)[1];
  // arr[0] : data:image/png;base64
  let mine = arr[0].split(";")[0].split(":")[1];
  let buffer = atob(arr[1]);
  let n = buffer.length;
  let u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = buffer.charCodeAt(n);
  }
  return new File([u8arr], fileName, {type: mine});
}

const postCarouselImg = (indexCarouselList) => {
  console.log(indexCarouselList)
  axios.post(`${ServerHost}/postIndexCarouselList`, {indexCarouselList: indexCarouselList})
      .then((res) => {
        isCarouselImgListSubmitting.value = false
        if (res.status === 200) {
          ElNotification({
            title: '轮播图提交成功',
            type: 'success',
            position: 'bottom-right',
          })
        } else {
          ElNotification({
            title: '轮播图提交失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

const verifyImg = (rawFile: File) => {
  if (!/^image\/(jpeg|png|jpg)$/.test(rawFile.type)
  ) {
    ElNotification({
      title: '图片格式不支持',
      type: 'warning',
      position: 'bottom-right',
    })
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElNotification({
      title: '图片超过2MB',
      type: 'warning',
      position: 'bottom-right',
    })
    return false
  }
  return true
}

const onUpdateUrl = (row: any) => {
  console.log(row)
  if (!row.row.url) {
    ElNotification({
      title: '链接不能为空',
      type: 'warning',
      position: 'bottom-right',
    })
    return
  }
  axios.post(`${ServerHost}/updateIndexCarousel`, {
    id: row.row.id,
    url: row.row.url
  })
      .then((res) => {
        console.log(row.row.url)
        if (res.status === 200) {
          ElNotification({
            title: '链接修改成功',
            type: 'success',
            position: 'bottom-right',
          })
        } else {
          ElNotification({
            title: '链接修改失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

</script>

<template>
  <div ref="observerDiv"></div>
  <el-tabs
      type="border-card"
      class="demo-tabs">
    <el-tab-pane label="图片管理">
      <div
          class="flex flex-col"
          v-loading="isCarouselImgListLoading">
        <VueDraggable
            class="flex flex-wrap shrink-0"
            v-model="carouseList"
            filter=".un-drag"
            v-loading="isCarouselImgListSubmitting"
            element-loading-text="正在提交…"
        >
          <!--  已有图片  -->
          <div
              class="carousel-img-upload"
              v-for="img in carouseList"
              :key="img.id">
            <el-upload
                drag
                :before-upload="onUpdateImg"
                :show-file-list="false"
                @click="onClickCarouselImgUpload(img.id)"
                data-id="{{img.id}}"
                :http-request="onImgUpload">
              <el-image class="carousel-img" fit="cover" :src="img.imgUrl" :alt="'img' + img.id"/>
            </el-upload>
            <el-icon class="carousel-img-delete" @click="onRemoveImg(img.id)">
              <Close/>
            </el-icon>
          </div>
          <!--  添加图片占位符  -->
          <el-upload
              drag
              class="carousel-img-upload un-drag"
              :before-upload="onAddImg"
              :show-file-list="false"
              :multiple="true"
              :http-request="onImgUpload"
          >
            <el-icon class="carousel-img-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </VueDraggable>
        <el-button :disabled="isCarouselImgListSubmitting" type="primary" @click="submitCarouselImg">提交轮播图
        </el-button>
      </div>
    </el-tab-pane>
    <el-tab-pane label="链接管理">
      <el-table
          :data="carouseList">
        <el-table-column label="序号">
          <template #default="row">
            <p>{{ row.$index + 1 }}</p>
          </template>
        </el-table-column>
        <el-table-column label="图片">
          <template #default="row">
            <el-image class="carousel-img" fit="cover" :src="row.row.imgUrl" :alt="'img'"/>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="链接">
          <template #default="row">
            <el-input v-model="row.row.url">
              <template #append>
                <el-button @click="onUpdateUrl(row)">修改</el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>

</template>

<style scoped lang="scss">

$carousel-img-size: 200px;

.carousel-img-upload, .carousel-img-uploader-icon {
  width: $carousel-img-size;
  height: $carousel-img-size;
  margin: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  border: 2px dashed var(--el-border-color);
  border-radius: 12px;
}

.carousel-img-upload:hover {
  border-color: var(--el-color-primary);

  .carousel-img-delete {
    display: block;
  }
}

.carousel-img {
  width: $carousel-img-size;
  height: $carousel-img-size;
}

.carousel-img-delete {
  margin-right: 10px;
  padding-top: 10px;
  padding-right: 10px;
  display: none;
  position: absolute;
  top: 0;
  right: 0;
}

</style>
